from flask import g, Blueprint, request, jsonify, session, redirect
from sqlalchemy import and_

from models import TeacherQuestionBankRel, Teacher, QuestionBank
from exts import db, get_time
from flask_login import login_required


bp = Blueprint("teacher_question_bank_rel", __name__, url_prefix="/teacher_question_bank_rel")


# todo before_request
@bp.before_request
@login_required
def before_request():
    pass


# todo query_teacher_in_bank
@bp.route("/query_teacher_in_bank")
def query_teacher_in_bank():
    id_question_bank = request.values.get("id_question_bank")
    return_data = []
    for i in db.session.query(TeacherQuestionBankRel).filter(TeacherQuestionBankRel.id_question_bank == id_question_bank).all():
        return_data.append({
            "id": i.teacher.id,
            "name": i.teacher.name,
            "phone": i.teacher.phone
        })

    data = {
        "code": 0,
        "msg": "",
        "count": len(db.session.query(TeacherQuestionBankRel).filter(TeacherQuestionBankRel.id_question_bank == id_question_bank).all()),
        "data": return_data
    }

    return jsonify(data)


# todo query_teacher_not_in_bank
@bp.route("/query_teacher_not_in_bank")
def query_teacher_not_in_bank():
    id_question_bank = request.values.get("id_question_bank")

    teacher = []
    for i in db.session.query(TeacherQuestionBankRel).filter(TeacherQuestionBankRel.id_question_bank == id_question_bank).all():
        teacher.append(i.teacher)

    return_data = []
    for i in db.session.query(Teacher).all():
        if i not in teacher:
            return_data.append({
                "id": i.id,
                "name": i.name,
                "phone": i.phone
            })

    data = {
        "code": 0,
        "msg": "",
        "count": len(return_data),
        "data": return_data
    }

    return jsonify(data)


# todo add_to_bank
@bp.route("/add_to_bank", methods=["POST"])
def add_to_bank():
    id_teacher = request.values.get("id_teacher")
    id_question_bank = request.values.get("id_question_bank")

    # print(id_teacher, id_question_bank)

    question_bank = db.session.query(QuestionBank).get(id_question_bank)
    teacher = db.session.query(Teacher).get(id_teacher)

    tqr = TeacherQuestionBankRel(
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0,
        question_bank=question_bank,
        teacher=teacher
    )

    db.session.add(tqr)
    db.session.commit()

    return "success"


# todo remove_from_bank
@bp.route("/remove_from_bank", methods=["POST"])
def remove_from_bank():
    id_teacher = request.values.get("id_teacher")
    id_question_bank = request.values.get("id_question_bank")

    db.session.query(TeacherQuestionBankRel).filter(and_(TeacherQuestionBankRel.id_question_bank == id_question_bank, TeacherQuestionBankRel.id_teacher == id_teacher)).delete()

    db.session.commit()

    return "success"
